package com.item.action;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.base.CoreConstants;
import com.base.dao.model.BFile;
import com.base.dao.model.BFileExample;
import com.base.service.BFileService;
import com.base.support.FileUpRetn;
import com.base.util.FileExportUtils;
import com.base.util.ImageUtils;
import com.base.util.MyOssClient;
import com.base.util.ResponseUtils;
import com.item.util.ConstantResources;
import com.item.util.MyFileExportUtils;
import com.item.util.MyImageUtils;
import com.mdx.mobile.commons.verfy.Md5;

@Controller
public class FileControllerNew extends CoreController{
	@Autowired
	BFileService fileService;
	private static final Logger logger = Logger.getLogger(FileControllerNew.class);
	
	private static final String BUCKET_NAME = CoreConstants.BUCKET_NAME_FRAMEWORK;

	@RequestMapping("/fileUploadNew")
	public void fileUpload(HttpServletRequest request, HttpServletResponse response,HttpSession session,String dir)
			throws Exception {
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");
		List<?> items = upload.parseRequest(request);
		Iterator<?> itr = items.iterator();
		String callback = request.getParameter("callback");
		while (itr.hasNext()) {
			FileItem item = (FileItem) itr.next();
			String fileName = item.getName();
			if (!item.isFormField()) {
				String md5 = Md5.md5(item.getInputStream());
				BFileExample example = new BFileExample();
				example.createCriteria().andFileMd5EqualTo(md5);
				List<BFile> lf = fileService.selectByExample(example);
				if (lf.size() > 0) {
					if(!StringUtils.isBlank(callback)){
						ResponseUtils.renderText(response, "<script>parent."+callback+"('"+lf.get(0).getFileId()+"')</script>");
						return;
					}
					if ("image".equals(dir)) {
						ResponseUtils.renderJson(response, new FileUpRetn(0, "download.do?id=" +lf.get(0).getFileId(), fileName, lf.get(0).getFileSize().longValue()));
						return;
					}
					ResponseUtils.renderJson(response, new FileUpRetn(0, lf.get(0).getFileId(), fileName, lf.get(0).getFileSize().longValue()));
					return;
				}
				long itemsize=item.getSize();
				// 检查文件大小
				if (itemsize >Long.parseLong(CoreConstants.FILE_MAXSIZE)) {
					if(!StringUtils.isBlank(callback)){
						ResponseUtils.renderText(response, "<script>parent."+callback+"(1)</script>");
						return;
					}
					ResponseUtils.renderJson(response, getError("上传文件大小超过限制。"));
					return;
				}
				// 检查扩展名
				String fileExt = fileName.substring(
						fileName.lastIndexOf(".") + 1).toLowerCase();
				String newFileName = UUID.randomUUID().toString()
						.replace("-", "");
				String minetype = FileExportUtils.getMine(fileName);
				
				if(fileName.endsWith(".apk")){
					minetype = "application/vnd.android.package-archive";
				}else if(fileName.endsWith(".ipa")){
					minetype = "application/iphone-package-archive";
				}
				
				try {
					Calendar cal=Calendar.getInstance();
					String realdir = cal.get(Calendar.YEAR)+"-"+(cal.get(Calendar.MONTH)+1)+"-"+(cal.get(Calendar.DAY_OF_MONTH))+"/"+minetype.replace("-", "")
							.replace("/", "_");
//					File f = new File(savePath, realdir);
//					if (!f.isDirectory()) {
//						f.mkdirs();
//					}
//					//写入文件
//					File uploadedFile = new File(f.getPath(), newFileName + "."
//							+ fileExt);
//					item.write(uploadedFile);
//					
					//写入阿里云
					MyOssClient.putObject(realdir + "/" + newFileName + "." + fileExt, item.getInputStream(), BUCKET_NAME);

					BFile ac = new BFile();
					ac.setFileId(newFileName);
					ac.setFileMinitype(minetype);
					ac.setFilePath(realdir + "/" + newFileName + "." + fileExt);
					ac.setFileState(1);
					ac.setFileSize(BigDecimal.valueOf(itemsize));
					ac.setFileMd5(md5);
					ac.setFileCreatetime(new Date());
					ac.setFileName(fileName);
					//ac.setFileBelong(getAppId(session));
					
					if(FileExportUtils.isImage(fileName)){
						BufferedImage bufferedImage = ImageIO.read(item.getInputStream());   
						int width = bufferedImage.getWidth();   
						int height = bufferedImage.getHeight();  
						ac.setFileCreater(width+"x"+height);
					}
					
					fileService.insert(ac);
				} catch (Exception e) {
					e.printStackTrace();
					if(!StringUtils.isBlank(callback)){
						ResponseUtils.renderText(response, "<script>parent."+callback+"(2)</script>");
						return;
					}
					ResponseUtils.renderJson(response, getError("上传文件失败。"));
					return;
				}
				if(!StringUtils.isBlank(callback)){
					ResponseUtils.renderText(response, "<script>parent."+callback+"('"+newFileName+"')</script>");
					return;
					
				}
				if ("image".equals(dir)) {
					newFileName = "download.do?id="+newFileName;
				}
				ResponseUtils.renderJson(response, new FileUpRetn(0, newFileName, fileName, itemsize));
				return;
			}
		}
		Map<String, Object> msg = new HashMap<String, Object>();
		msg.put("error", 1);
		msg.put("message", "没有发现文件域");
		if(!StringUtils.isBlank(callback)){
			ResponseUtils.renderText(response, "<script>parent."+callback+"(3)</script>");
			return;
		}
		ResponseUtils.renderJson(response, msg);
		return;
	}
	
	@RequestMapping("/downloadNew")
	public void downloadFile(String id,HttpServletResponse resp,
			@RequestParam(value = "w", required = false) String w,
			@RequestParam(value = "h", required = false) String h,String type) throws Exception{
		if(id!=null){
			BFile item = fileService.selectByPrimaryKey(id);
			if (item == null) {
				throw new Exception("文件不存在");
			} else {
				String realFilePath = item.getFilePath();
				int width = 0, height = 0;
				if (w != null && w.length() > 0) {
					width = Integer.valueOf(w);
				}
				if (h != null && h.length() > 0) {
					height = Integer.valueOf(h);
				}
				long start = System.currentTimeMillis();
				if (width != 0 && item.getFileMinitype().startsWith("image")) {
					String fileExt = item.getFileName().substring(
							item.getFileName().lastIndexOf(".") + 1).toLowerCase();
					String tf ="temp/" +  item.getFileMd5() +"_"+ width + "x" + height + ""+ fileExt;
					realFilePath = tf;
					byte[] tempData = MyOssClient.getObject(tf, BUCKET_NAME);
					if (tempData == null) {
						InputStream bi = MyOssClient.getObjectStream(item.getFilePath(), BUCKET_NAME);
						if(bi != null) {
							BufferedImage bimg = ImageIO.read(bi);
							bi.close(); //关闭流
							if (height == 0) {
								tempData = MyImageUtils.Compress(bimg, tf, fileExt,width, BUCKET_NAME);
							} else {
								tempData = MyImageUtils.Compress(bimg, tf, fileExt,width, height, BUCKET_NAME);
							}
						}	
					}
					//如果没有进行压缩，说明直接返回的是原图
					if(tempData == null) 
						realFilePath = item.getFilePath();
				}
				resp.setContentType(item.getFileMinitype() + "; charset=utf-8");
				//重定向，交给APACHE处理
				MyFileExportUtils.downloadNew(resp, realFilePath);
//				FileExportUtils.download(resp, item.getFileName(), item.getFileMinitype(), fileData,type);
			}
		}
	}
	
	private FileUpRetn getError(String message) {
		return new FileUpRetn(1, message);
	}
}
